﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDemo.Models;
using System.Reflection;

namespace MvcDemo.Controllers
{
    public class JsonController : Controller
    {
        //
        // GET: /Json/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CustomersList()
        {
            var db = new CustomerDataContext();
            var q = from c in db.Customers
                    select c;

            List<Customer> customers = q.ToList();
            FlexigridObject flexigridObject = new FlexigridObject();
            flexigridObject.page = 1;
            flexigridObject.total = db.Customers.Count();
            foreach (Customer customer in customers)
            {
                FlexigridRow row = new FlexigridRow()
                {
                    id = customer.CustomerID,
                    cell = GetPropertyList(customer)
                };
                flexigridObject.rows.Add(row);
            }
            return PartialView("FlexigridObjectPartial", flexigridObject);
        }

        private List<string> GetPropertyList(object obj)
        {
            List<string> propertyList = new List<string>();

            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
                                                            BindingFlags.Public);
            foreach (PropertyInfo property in properties)
            {
                object o = property.GetValue(obj, null);
                propertyList.Add(o == null ? "" : o.ToString());
            }
            return propertyList;
        }

    }
}
